const Print = function (dom, options) {
  if (!(this instanceof Print)) {
    return new Print(dom, options)
  }
  this.options = Object.assign({
    'noPrint': '.no-print'
  }, options)

  if ((typeof dom) === 'string') {
    this.dom = document.querySelector(dom)
  } else {
    this.dom = this.isDOM(dom) ? dom : dom.$el
  }
  this.init()
}
Print.prototype = {
  init: function () {
    const content = this.getStyle() + this.setStyle() + this.getHtml()
    this.writeIframe(content)
  },
  // 获取样式
  getStyle: function () {
    let styleStr = ''
    const styles = document.querySelectorAll('style,link')
    for (let i = 0; i < styles.length; i++) {
      styleStr += styles[i].outerHTML
    }
    styleStr += `<style>
      ${this.options.noPrint ? this.options.noPrint : '.noPrint'} {display: none;}
    </style>`
    return styleStr
  },
  // 根据用户需求设置页眉页脚，并修复折行和拆表等问题
  setStyle: function() {
    const noHeader = this.options.noHeader || false
    const noFooter = this.options.noFooter || false
    return `<style>
      ${
        (noFooter || noFooter) ? `
          @media print {
            @page {
              size: auto;
              /* auto is the initial value */
              margin-top: 10mm;
              margin-left: 10mm;
              margin-right: 10mm;
              margin-bottom: 10mm;
            }
          }
        ` : ''
      }
      ${
        noHeader ? `
          @media print {
            @page {
              margin-top: 0mm;
            }
          }
        ` : '' 
      }
      ${
        noFooter ? `
          @media print {
            @page {
              margin-bottom: 0mm;
            }
          }
        ` : '' 
      }
    </style>`
  },
  // 获取HTMl
  getHtml: function () {
    const inputs = document.querySelectorAll('input')
    const textareas = document.querySelectorAll('textarea')
    const selects = document.querySelectorAll('select')

    // 拷贝input元素值
    for (let i = 0; i < inputs.length; i++) {
      const { type, checked, value } = inputs[i]
      if (type === 'checkbox' || type === 'radio') {
        if (checked === true) {
          inputs[i].setAttribute('checked', 'checked')
        } else {
          inputs[i].removeAttribute('checked')
        }
      } else {
        inputs[i].setAttribute('value', value)
      }
    }
    // 拷贝textarea值
    for (let j = 0; j < textareas.length; j++) {
      if (textareas[j].type === 'textarea') {
        textareas[j].innerHTML = textareas[j].value
      }
    }
    // 拷贝select值
    for (let k = 0; k < selects.length; k++) {
      if (selects[k].type === 'select-one') {
        const { children } = selects[k]
        for (const index in children) {
          const child = children[index]
          if (child.tagName === 'OPTION') {
            if (child.selected === true) {
              child.setAttribute('selected', 'selected')
            } else {
              child[i].removeAttribute('selected')
            }
          }
        }
      }
    }
    return this.dom.outerHTML
  },
  // 将获取和拷贝的值在iframe中渲染
  writeIframe: function (content) {
    const iframe = document.createElement('iframe')
    iframe.id = 'myIframe'
    iframe.setAttribute('style', 'position:absolute;width:0;height:0;top:-10px;left:-10px;')

    const iframeDom = document.body.appendChild(iframe)
    const iframeWindow = iframeDom.contentWindow || iframeDom.contentDocument
    const iframeDoc = iframeDom.contentDocument || iframeDom.contentWindow.document

    iframeDoc.open()
    iframeDoc.write(content)
    iframeDoc.close()
    const self = this
    iframe.onload = function () {
      self.toPrint(iframeWindow)
      setTimeout(() => {
        document.body.removeChild(iframe)
      }, 0)
    }
  },
  toPrint: function (window) {
    try {
      setTimeout(() => {
        window.focus()
        try {
          if (!window.document.execCommand('print', false, null)) {
            window.print()
          }
        } catch (e) {
          window.print()
        }
        window.close
      }, 0)
    } catch (error) {
      console.error('error', error)
    }
  },
  isDOM: function (obj) {
    if (typeof HTMLElement === 'object') {
      return obj instanceof HTMLElement
    }
    return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string'
  }
}
const VuePrinter = {
  install: function (_Vue) {
    _Vue.prototype.$print = Print
  }
}
export default VuePrinter